package main

import (
	"crypto/tls"
	"crypto/x509"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"net/http"
)

func loadCA(caFile string) *x509.CertPool {
	pool := x509.NewCertPool()

	if ca, e := ioutil.ReadFile(caFile); e != nil {
		log.Fatal("ReadFile: ", e)
	} else {
		pool.AppendCertsFromPEM(ca)
	}
	return pool
}

func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
		io.WriteString(w, "hello, world!\n")
	})
	fmt.Println("Running")

	cfg := &tls.Config{
		ClientCAs:  loadCA("tls/ca.crt"),
		ClientAuth: tls.RequireAndVerifyClientCert,
	}
	var server http.Server
	server.TLSConfig = cfg
	server.Addr = ":9443"
	if e := server.ListenAndServeTLS("tls/server.crt", "tls/server.key"); e != nil {
		log.Fatal("ListenAndServe: ", e)
	}
}
